package com.lwei.tallybook.client.controller;

import com.lwei.tallybook.base.domain.Account;
import com.lwei.tallybook.base.dto.Message;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 系统控制器
 * @author sks.lwei
 */
@Log4j2
@RestController
@RequestMapping("/api/home")
public class HomeController extends BaseController{

    /**
     * 获取所有人
     * //所有吃饭的人
     */
    @RequestMapping("/get-all-account")
    public Message listAllAccount(){
        List<Account> accounts = accountService.listAll();
        return Message.data(accounts);
    }

    /**
     * 登录验证
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Message login(@RequestParam String loginName, @RequestParam String password){

        //默认记住我
        AuthenticationToken token = new UsernamePasswordToken(loginName, password);
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(token);
        } catch (UnknownAccountException e){
            log.warn("{}:登录失败，用户不存在！", loginName);
            return Message.FAIL;
        } catch (IncorrectCredentialsException e2){
            log.warn("{}:登录失败，密码错误！", loginName);
            return Message.failMsg("密码错误");
        } catch (Exception e3){
            log.error(e3);
            return Message.FAIL;
        }

        if(subject.isAuthenticated()){
            return Message.SUCCESS;
        }else {
            return Message.FAIL;
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Message logout(){
        return Message.SUCCESS;
    }
}
